package com.wangxiaoxuan.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wangxiaoxuan.seckill.Util.Md5Util;
import com.wangxiaoxuan.seckill.Util.UUIDUtil;
import com.wangxiaoxuan.seckill.pojo.*;
import com.wangxiaoxuan.seckill.mapper.OrderMapper;
import com.wangxiaoxuan.seckill.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangxiaoxuan.seckill.service.ISeckillGoodsService;
import com.wangxiaoxuan.seckill.service.ISeckillOrderService;
import com.wangxiaoxuan.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangxiaoxuan
 * @since 2022-03-23
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
   @Autowired
   private OrderMapper orderMapper;
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 秒杀
     * @param user
     * @param goodsVo
     * @return
     */
    @Override
    @Transactional//开启事务
    public Order seckill(User user, GoodsVo goodsVo) {
        //拿到秒杀商品
        SeckillGoods seckillGoods =
                seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));
        //给库存-1
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);

       // 解决超卖：update seckille_goods set stock_count=stock_count+1 where goods_id=#{id} and stock_count>0
       Boolean res= seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count"+"stock_count-1")
                .eq("goods_id", goodsVo.getId()).gt("stock_count",0));
       if (!res){
           return null;
       }
        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goodsVo.getGoodsPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrderService.save(seckillOrder);
        return order;
    }

    /**
     * 插入订单
     * @param order
     * @return 返回订单id
     */
    @Override
    @Transactional
    public Long insertOrder(Order order) {
        orderMapper.insert(order);
        return order.getId();
    }

    /**
     * 支付超时删除订单
     * @param order
     * @return
     */
    @Override
    public int deleteOrderTimeOut(Order order) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",order.getUserId())
                .eq("goods_id",order.getGoodsId());
        return orderMapper.delete(queryWrapper);
    }
    /**
     * 支付成功，同步数据
     * @param map
     * @return
     */
    @Override
    public int updatePayStatus(Map<String, String> map) {
        return orderMapper.updatePayStatus(map);
    }

    /**
     * 秒杀接口地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {

        String str = Md5Util.md5(UUIDUtil.uuid()+"123456");
        redisTemplate.opsForValue().set("seckillPath"+user.getId()+":"+goodsId,str,60, TimeUnit.SECONDS);
        return str;

    }

    /**
     * 校验秒杀接口
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {
        if (user==null||goodsId<0||path==null){
            return false;
        }
        String str = (String) redisTemplate.opsForValue().get("seckillPath" + user.getId() + ":" + goodsId);
        return path.equals(str);
    }
}
